import { getCanvasContext } from '@/utils/file'
import type { PDFDocumentProxy, PDFPageProxy } from 'pdfjs-dist'
import type { RenderParameters } from 'pdfjs-dist/types/src/display/api'
import PptxGenJS from 'pptxgenjs'

export const usePdf2Ppt = () => {
  let pptx: PptxGenJS = new PptxGenJS()

  // 解析pdf
  const parsePDF = async () => {}

  // 用canvas渲染
  const renderPageWithCanvas = async (page: PDFPageProxy) => {
    const viewport = page.getViewport({ scale: 1.0 })
    const { context } = getCanvasContext(viewport.width, viewport.height)
    const renderContext: RenderParameters = {
      canvasContext: context,
      viewport: viewport,
    }
    await page.render(renderContext).promise
  }

  // 转换pdf
  const transferPDF2Ppt = async (pdf: PDFDocumentProxy) => {
    const numPages = pdf.numPages
    for (let i = 1; i <= numPages; i++) {
      const page = await pdf.getPage(i)
      await renderPageWithCanvas(page)
      // 创建ppt页面
      const slide = pptx.addSlide()
      const textContent = await page.getTextContent()
      slide.addText(
        textContent.items.map((item: RecordRaw) => {
          return {
            text: item.str?.length ? item.str : '\r\n',
            options: {
              rtlMode: item.dir !== 'ltr',
              fontFace: textContent.styles[item.fontName].fontFamily,
              fontSize: item.height,
              line: {
                width: item.width,
              },
            },
          }
        }),
      )
    }
  }

  // 保存ppt
  const savePpt = async (fileName: string) => {
    await pptx.writeFile({ fileName })
  }

  return {
    parsePDF,
    transferPDF2Ppt,
    savePpt,
  }
}
